package com.example.mybaseapp.ui.fragment.recommand


import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.mybaseapp.R
import com.example.mybaseapp.databinding.ItemPaletteRecommandBinding


class PaletteRecommandAdapter( var datas: ArrayList<PaletteRecommandBean>) : RecyclerView.Adapter<PaletteRecommandAdapter.RecommandViewHolder>(
) {
    private var currentPosition=0

    inner class RecommandViewHolder(val binding: ItemPaletteRecommandBinding):RecyclerView.ViewHolder(binding.root){

        fun bindDetail(bean: PaletteRecommandBean, position: Int){
            binding.icoImg.setImageResource(bean.drawableResource)
            binding.tx.text = bean.title
            if(bean.selectStatus){
                val colorStateList = ColorStateList.valueOf(ContextCompat.getColor(binding.root.context, R.color.final_blue))
                binding.icoImgForeground.isVisible = true
                binding.tx.setTextColor(colorStateList)
            }else{
                val colorStateList = ColorStateList.valueOf(ContextCompat.getColor(binding.root.context, R.color.white_87))
                binding.icoImgForeground.isVisible = false
                binding.tx.setTextColor(colorStateList)
            }
            binding.constraint.tag = position
            binding.constraint.setOnClickListener {
                currentPosition = it.tag as Int
                changeSelect()
            }
        }

        private fun changeSelect() {
            datas.forEachIndexed{i,p->
                if(p.selectStatus){
                    if(i!=currentPosition){
                        p.selectStatus = false
                        notifyItemChanged(i)
                    }
                }else{
                    if(i==currentPosition){
                        p.selectStatus = true
                        notifyItemChanged(i)
                    }
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecommandViewHolder {
        return RecommandViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_palette_recommand, null, false))
    }

    override fun onBindViewHolder(holder: RecommandViewHolder, position: Int) {
        holder.bindDetail(datas[position],position)
    }

    override fun getItemCount(): Int {
        return datas.size
    }
}